﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using RabbitMQ.Client;

namespace YEA.Infrastructure.Gateway.Converter
{
    public class StringToMessageConverter : IConvertToMessage
    {
        public static readonly string PLAIN_TEXT = "text/plain";
        public const string _defaultCharSet = "utf-8";

        public string CharSet { get; set; }

        public StringToMessageConverter()
        {
            CharSet = _defaultCharSet;
        }

        public virtual Message ConvertObjectToMessage(RabbitMQ.Client.IModel channel, object packetToSend)
        {
            if (!(packetToSend is string))
                throw new ApplicationException("paketToSend has to be a string to convert to a Message using this converter");
            if (channel == null)
                throw new ApplicationException("The channel is null, a valid channel is required to create a message");
            var properties = channel.CreateBasicProperties();
            properties.Headers = new Dictionary<string, object>();
            var bytes = Encoding.GetEncoding(CharSet).GetBytes((string)packetToSend);
            properties.ContentType = PLAIN_TEXT;
            properties.ContentEncoding = CharSet;
            return new Message() { Body = bytes, Properties = properties, RoutingKey = string.Empty };

        }
    }
}
